package puj.promobil.prometer;

import java.io.ByteArrayOutputStream;
import java.sql.SQLException;
import java.text.NumberFormat;

import puj.promobil.prometer.dto.Imagen;
import puj.promobil.prometer.dto.Medida;
import puj.promobil.prometer.dto.MedidaSolicitud;
import puj.promobil.prometer.dto.Producto;
import puj.promobil.prometer.persistence.DatabaseManager;
import puj.promobil.prometer.webservices.mobileclient.PrometerMobileWSClientTestTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MedirActivity extends Activity implements View.OnTouchListener {

	private float x1 = -1;
	private float y1 = -1;
	private float x2 = -1;
	private float y2 = -1;

	private float x3 = -1;
	private float y3 = -1;
	private float x4 = -1;
	private float y4 = -1;

	private int punto = 1;

	private Bitmap bh;

	private Bitmap bha;

	Lienzo fondo;

	private Canvas canvas1;

	private Medida medidaRespuesta;
	
	private int idProducto;
	
	private Producto producto;
	
	private int idImagenActual;
	
	private Imagen imagenActual;
	
	private ToggleButton dimensiones;
	
	private TextView alto, ancho, profundidad;
	
	private NumberFormat formatter;
	
	private boolean guardar=false;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_medir);
		
		
		
		this.handleTakeMeasure(this.getIntent());

		DatabaseManager.init(this);
		
		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mycanvas);
		
		dimensiones = (ToggleButton) findViewById(R.id.orientacion);
		
		alto = (TextView) findViewById(R.id.alto);
		
		ancho = (TextView) findViewById(R.id.ancho);
		
		profundidad = (TextView) findViewById(R.id.profundidad);
		
		formatter=NumberFormat.getIntegerInstance();
		
		try {
			imagenActual = DatabaseManager.getInstance().getImagen(idImagenActual);
			producto = DatabaseManager.getInstance().getProducto(idProducto);
			
			alto.setText("Alto: "+formatter.format(this.producto.getAlto())+" mm | ");
			ancho.setText("Ancho: "+formatter.format(this.producto.getAncho())+" mm | ");
			profundidad.setText("Profund: "+formatter.format(this.producto.getProfundidad())+" mm");
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
	    bh = BitmapFactory.decodeByteArray(imagenActual.getImagen(),0,imagenActual.getImagen().length);		

		fondo = new Lienzo(this);

		fondo.setOnTouchListener(this);
		linearLayout.addView(fondo);
		
		
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_medir, menu);
		return true;
	}

	@Override
	public boolean onTouch(View view, MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (punto > 2) {
				punto = 1;
			}
			if (punto == 1) {
				x1 = event.getX();
				y1 = event.getY();
				x2 = -1;
				y2 = -1;
				x3 = -1;
				y3 = -1;
				x4 = -1;
				y4 = -1;
			} else {
				x3 = event.getX();
				y3 = event.getY();
				x4 = -1;
				y4 = -1;
			}
			fondo.postInvalidate();
			// Toast.makeText(this, "onTouch: " + x1 + ", " +
			// y1,Toast.LENGTH_SHORT).show();
			break;
		case MotionEvent.ACTION_UP:
			if (punto == 1) {
				x2 = event.getX();
				y2 = event.getY();

				int x1t = (int) Math.min(x1, x2);
				int x2t = (int) Math.max(x1, x2);
				int y1t = (int) Math.min(y1, y2);
				int y2t = (int) Math.max(y1, y2);
				x1 = x1t;
				x2 = x2t;
				y1 = y1t;
				y2 = y2t;

			} else {
				x4 = event.getX();
				y4 = event.getY();

				int x3t = (int) Math.min(x3, x4);
				int x4t = (int) Math.max(x3, x4);
				int y3t = (int) Math.min(y3, y4);
				int y4t = (int) Math.max(y3, y4);
				x3 = x3t;
				x4 = x4t;
				y3 = y3t;
				y4 = y4t;

			}

			punto++;

			fondo.postInvalidate();

			break;
		}

		return true;
	}

	
	public void guardarMedida(View view){
		
		if(!guardar){
			Toast.makeText(this.getBaseContext(), "Antes de almacenar debe realizar una medida.",Toast.LENGTH_SHORT).show();
			return;
		}
		
		if(dimensiones.getText().equals(this.getString(R.string.toogle_alto_ancho))){
			producto.setAlto(this.medidaRespuesta.getAlto());
			producto.setAncho(this.medidaRespuesta.getAncho());
			
			alto.setText("Alto: "+formatter.format(this.medidaRespuesta.getAlto())+" mm  | ");
			ancho.setText("Ancho: "+formatter.format(this.medidaRespuesta.getAncho())+" mm | ");
			profundidad.setText("Profund: "+formatter.format(this.producto.getProfundidad())+" mm");
			
		}
		else{
			producto.setAlto(this.medidaRespuesta.getAlto());
			producto.setProfundidad(this.medidaRespuesta.getAncho());

			alto.setText("Alto: "+formatter.format(this.medidaRespuesta.getAlto())+" mm  | ");
			ancho.setText("Ancho: "+formatter.format(this.producto.getAncho())+" mm  | ");
			profundidad.setText("Profund: "+formatter.format(this.medidaRespuesta.getAncho())+" mm");

		}
		
		try {
			DatabaseManager.getInstance().updateProducto(producto);
			Imagen tmp=new Imagen();
			tmp.setProducto(producto);
			tmp.setImagen(this.medidaRespuesta.getData());
			DatabaseManager.getInstance().addImagen(tmp);
			Toast.makeText(this.getBaseContext(), "Almacenamiento exitoso",Toast.LENGTH_SHORT).show();
			
		} catch (Exception e) {
			
			Toast.makeText(this.getBaseContext(), "Error al almacenar: "+ e.getMessage(),
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		
		
		this.finishActivity(4);
	}
	
	public void cancelarMedida(View view){
		this.finish();
	}

	

	public void medirEvento(View view) {

		try {
			// PrometerMobileWSClient client;
			MedidaSolicitud medicion = new MedidaSolicitud();

			ByteArrayOutputStream out = new ByteArrayOutputStream();

			bh.compress(Bitmap.CompressFormat.JPEG, 100, out);

			medicion.setData(out.toByteArray());

			medicion.setAlto(bh.getHeight());

			medicion.setAncho(bh.getWidth());

			medicion.setX1((int) x1 * bh.getWidth() / bha.getWidth());

			medicion.setX2((int) x2 * bh.getWidth() / bha.getWidth());

			medicion.setX3((int) x3 * bh.getWidth() / bha.getWidth());

			medicion.setX4((int) x4 * bh.getWidth() / bha.getWidth());

			medicion.setY1((int) y1 * bh.getHeight() / bha.getHeight());

			medicion.setY2((int) y2 * bh.getHeight() / bha.getHeight());

			medicion.setY3((int) y3 * bh.getHeight() / bha.getHeight());

			medicion.setY4((int) y4 * bh.getHeight() / bha.getHeight());

			medicion.setRef(20);

			String url=DatabaseManager.getInstance().getConfiguracion().getServicio();
			
			PrometerMobileWSClientTestTask task = new PrometerMobileWSClientTestTask(
					this, url, medicion);
			task.execute();

		} catch (Exception e) {

			String error = e.getMessage();
			if (error == null) {
				error = e.toString();
			}
			Toast.makeText(this, "Error: " + error, Toast.LENGTH_SHORT).show();
		}
	}

	public void setMedida(Medida medidaRespuesta) {

		guardar=true;
		
		this.medidaRespuesta = medidaRespuesta;

		canvas1 = new Canvas(bha);

		canvas1.drawRGB(0, 0, 255);

		bh = BitmapFactory.decodeByteArray(medidaRespuesta.getData(),
				0, medidaRespuesta.getData().length);

		/*tmp = redimensionarImagenMaximo(tmp, fondo.getWidth(),
				fondo.getHeight());

		Paint p = new Paint();

		canvas1.drawBitmap(tmp, 0, 0, p);
		*/
		
		if(dimensiones.getText().equals(this.getString(R.string.toogle_alto_ancho))){
			alto.setText("Alto: "+formatter.format(this.medidaRespuesta.getAlto())+" mm  | ");
			ancho.setText("Ancho: "+formatter.format(this.medidaRespuesta.getAncho())+" mm | ");
			profundidad.setText("Profund: "+formatter.format(this.producto.getProfundidad())+" mm");
			
		}
		else{
			alto.setText("Alto: "+formatter.format(this.medidaRespuesta.getAlto())+" mm  | ");
			ancho.setText("Ancho: "+formatter.format(this.producto.getAncho())+" mm  | ");
			profundidad.setText("Profund: "+formatter.format(this.medidaRespuesta.getAncho())+" mm");
		}
		
		x1 = -1;
		y1 = -1;
		x2 = -1;
		y2 = -1;
		x3 = -1;
		y3 = -1;
		x4 = -1;
		y4 = -1;
		
		fondo.postInvalidate();

	}

	public Bitmap redimensionarImagenMaximo(Bitmap mBitmap, float newWidth,
			float newHeigth) {
		// Redimensionamos
		int width = mBitmap.getWidth();
		int height = mBitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeigth) / height;
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);
		
		return Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, false);
		
		/*
		// recreate the new Bitmap
		Bitmap b1 = Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, false);
		
		Bitmap b2 = Bitmap.createBitmap((int)newWidth,(int)newHeigth,b1.getConfig());
		Canvas cam = new Canvas(b2);
		
		Paint p = new Paint();		
		cam.drawBitmap(b1, (b2.getWidth()-b1.getWidth())/2, 0, p);
		//cam.drawBitmap(bitmap, matrix, paint)
		
		
		
		return b2; */
	}

	class Lienzo extends View {
		public Lienzo(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}

		protected void onDraw(Canvas canvas) {

			canvas1 = canvas;

			canvas.drawRGB(0, 0, 255);
			// int ancho=canvas.getWidth();
			// int alto=canvas.getHeight();
			// Bitmap bmp=BitmapFactory.decodeResource(getResources(),
			// R.drawable.imagen1);
			// canvas.drawBitmap(bmp, (ancho-250)/2,(alto-200)/2, null);

			canvas.drawColor(Color.BLACK);
			Paint p = new Paint();
			p.setColor(Color.RED);
			p.setStrokeWidth(8);
			p.setStyle(Style.STROKE);
			
			/*if(bh.getHeight()<=250){
				int h=(int)(bh.getHeight()*1.4);
				int w=(int)(bh.getWidth()*1.4);
				bha = redimensionarImagenMaximo(bh, w,h);
			}
			else{*/
				bha = redimensionarImagenMaximo(bh, fondo.getHeight(),fondo.getHeight());
			//}

			

			// canvas.drawBitmap(bha,
			// (ancho-bh.getWidth())/2,(alto-bh.getHeight())/2, p);

			canvas.drawBitmap(bha, 0, 0, p);

			p.setStrokeWidth(2);

			if (!(x1 == -1 || y1 == -1 || x2 == -1 || y2 == -1)) {
				canvas.drawRect(x1, y1, x2, y2, p);
			}

			p.setColor(Color.GREEN);

			p.setStrokeWidth(2);

			if (!(x3 == -1 || y3 == -1 || x4 == -1 || y4 == -1)) {
				canvas.drawRect(x3, y3, x4, y4, p);
			}

		}

	}
	
	
	private void handleTakeMeasure(Intent intent) {

		Bundle extras = intent.getExtras();
		idProducto = Integer.parseInt((String) extras.get("idproducto"));
		idImagenActual = Integer.parseInt((String) extras.get("idImagenActual"));
	}
	

	
	public Bitmap getBh() {
		return bh;
	}

	public void setBh(Bitmap bh) {
		this.bh = bh;
	}

}
